package com.exam.sacrifice.ui.mine;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.exam.commonbiz.base.BaseActivity;
import com.exam.commonbiz.base.BaseViewModel;
import com.exam.commonbiz.util.OnFastClickListener;
import com.exam.sacrifice.R;
import com.exam.sacrifice.databinding.ActivityPrivacySettingsBinding;

import java.io.File;

public class PrivacySettingsActivity extends BaseActivity<BaseViewModel, ActivityPrivacySettingsBinding> {
    private SwitchCompat switchDataCollection;
    private SwitchCompat switchPersonalizedAds;
    private SwitchCompat switchAnalytics;
    private SwitchCompat switchLocationTracking;
    private Button btnPermissionManager;
    private Button btnPrivacyPolicy;
    private Button btnClearData;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_privacy_settings;
    }

    @Override
    public void initData() {

        binding.include.tvTitle.setText("隐私设置");
        binding.include.ivback.setOnClickListener(new OnFastClickListener() {
            @Override
            public void onFastClick(View v) {
                finish();
            }
        });

        initViews();
        loadSettings();
        setListeners();
    }

    private void initViews() {
        switchDataCollection = findViewById(R.id.switch_data_collection);
        switchPersonalizedAds = findViewById(R.id.switch_personalized_ads);
        switchAnalytics = findViewById(R.id.switch_analytics);
        switchLocationTracking = findViewById(R.id.switch_location_tracking);
        btnPermissionManager = findViewById(R.id.btn_permission_manager);
        btnPrivacyPolicy = findViewById(R.id.btn_privacy_policy);
        btnClearData = findViewById(R.id.btn_clear_data);
    }

    private void loadSettings() {
        // 从SharedPreferences加载设置
        SharedPreferences prefs = getSharedPreferences("privacy_prefs", MODE_PRIVATE);

        switchDataCollection.setChecked(prefs.getBoolean("data_collection", true));
        switchPersonalizedAds.setChecked(prefs.getBoolean("personalized_ads", true));
        switchAnalytics.setChecked(prefs.getBoolean("analytics", true));
        switchLocationTracking.setChecked(prefs.getBoolean("location_tracking", false));
    }

    private void setListeners() {
        // 数据收集开关
        switchDataCollection.setOnCheckedChangeListener((buttonView, isChecked) -> {
            saveSetting("data_collection", isChecked);
            // 如果关闭数据收集，自动关闭相关选项
            if (!isChecked) {
                switchPersonalizedAds.setChecked(false);
                switchAnalytics.setChecked(false);
                switchLocationTracking.setChecked(false);
                saveSetting("personalized_ads", false);
                saveSetting("analytics", false);
                saveSetting("location_tracking", false);
            }
        });

        // 个性化广告开关
        switchPersonalizedAds.setOnCheckedChangeListener((buttonView, isChecked) -> {
            saveSetting("personalized_ads", isChecked);
            // 如果开启个性化广告，需要确保数据收集是开启的
            if (isChecked && !switchDataCollection.isChecked()) {
                switchDataCollection.setChecked(true);
                saveSetting("data_collection", true);
            }
        });

        // 分析数据开关
        switchAnalytics.setOnCheckedChangeListener((buttonView, isChecked) -> {
            saveSetting("analytics", isChecked);
            // 如果开启分析数据，需要确保数据收集是开启的
            if (isChecked && !switchDataCollection.isChecked()) {
                switchDataCollection.setChecked(true);
                saveSetting("data_collection", true);
            }
        });

        // 位置跟踪开关
        switchLocationTracking.setOnCheckedChangeListener((buttonView, isChecked) -> {
            saveSetting("location_tracking", isChecked);
            if (isChecked) {
                // 检查位置权限
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            1001);
                }
            }
        });

        // 权限管理
        btnPermissionManager.setOnClickListener(v -> {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.fromParts("package", getPackageName(), null));
            startActivity(intent);
        });

        // 隐私政策
        btnPrivacyPolicy.setOnClickListener(v -> {

        });

        // 清除数据
        btnClearData.setOnClickListener(v -> showClearDataDialog());
    }

    private void saveSetting(String key, boolean value) {
        SharedPreferences prefs = getSharedPreferences("privacy_prefs", MODE_PRIVATE);
        prefs.edit().putBoolean(key, value).apply();

        // 这里应该同步到服务器（如果有的话）
        // syncSettingsToServer();
    }

    private void showClearDataDialog() {
        new AlertDialog.Builder(this)
                .setTitle("清除数据")
                .setMessage("确定要清除所有本地数据吗？此操作不可撤销。")
                .setPositiveButton("清除", (dialog, which) -> clearAppData())
                .setNegativeButton("取消", null)
                .show();
    }

    private void clearAppData() {
        // 清除SharedPreferences
        SharedPreferences prefs = getSharedPreferences("privacy_prefs", MODE_PRIVATE);
        prefs.edit().clear().apply();

        // 清除缓存
        try {
            File cacheDir = getCacheDir();
            File appDir = new File(cacheDir.getParent());
            if (appDir.exists()) {
                String[] children = appDir.list();
                for (String s : children) {
                    if (!s.equals("lib")) {
                        deleteDir(new File(appDir, s));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 重置开关状态
        loadSettings();

        Toast.makeText(this, "数据已清除", Toast.LENGTH_SHORT).show();
    }

    private boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (String child : children) {
                boolean success = deleteDir(new File(dir, child));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1001) {
            if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                switchLocationTracking.setChecked(false);
                saveSetting("location_tracking", false);
                Toast.makeText(this, "位置权限被拒绝，无法启用位置跟踪", Toast.LENGTH_SHORT).show();
            }
        }
    }
}